var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');


// 引入环境变量
require('dotenv').config();
require('express-async-errors') //用于处理异步错误的中间件
var expressJWT = require("express-jwt");
const {ForbiddenError} =require('./utils/error')
// 引入数据库
require('./dao/db.js')
var adminRouter = require('./routes/admin');
const md5 = require('md5')
// 引入错误类
require('./utils/error.js')

var app = express();



app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// 配置验证token接口
app.use(expressJWT.expressjwt({ 
  secret: md5(process.env.JWT_SECRET), 
  algorithms: ['HS256'] 
}).unless({
  path: [ '/admin/login8']
}));
app.use('/admin', adminRouter);


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  console.log("err.name",err.name);
  console.log("err.message",err.message);
  if (err.name === "UnauthorizedError") {
    // 说明是401错误
    res.send(new ForbiddenError("token已过期，请重新登录").toResponseJSON())
  }else if(err instanceof ServiceError){
    res.send(err.toResponseJSON())
  }else{
    res.send(new UnknownError().toResponseJSON)
  }
});

module.exports = app;
